import React, { Component } from "react";
import { SafeAreaView, Text, View, StyleSheet, Image, TextInput, TouchableOpacity, FlatList, ActivityIndicator, DeviceEventEmitter } from 'react-native';

import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, formatTimestamp, getMsgContentShow, getPriceFormat, getCarRegisterDate, getMileFormat } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import Loading from "../../utils/Loading";
import OpenIMSDKRN, { OpenIMEmitter, MessageItem } from 'open-im-sdk-rn';
import AsyncImage from '../../components/image/AsyncImage'

let navigation
/**
 * 系统通知消息
 */
export default class NoticeMsgListPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            msgList: [],
            pageNo: 1,
            msgType: this.props.route && this.props.route.params && this.props.route.params.msgType ? this.props.route.params.msgType : '',
            title: this.props.route && this.props.route.params && this.props.route.params.title ? this.props.route.params.title : '消息通知',
            isRefresh: false,
            showFoot: 0,
            keyWord: '',
            isFirstLoad: true

        };
        this.flatListRef = React.createRef();
    }

    componentDidMount() {


        if (this.Loading) {
            this.Loading.show()
        }
        this.getMsgList()
    }

    componentWillUnmount() {

    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} isAtRoot={false} Title={this.state.title} hideSepLine={true} bgColor={'#ffffff'}></Header>



                <FlatList
                    ref={this.flatListRef}
                    data={this.state.msgList}
                    renderItem={this.renderMsgItem.bind(this)}
                    keyExtractor={(item, index) => index + ''}
                    style={{ flex: 1, backgroundColor: '#fff', width: '100%' }}
                    extraData={this.state}
                    ListFooterComponent={this._renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.1}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                >

                </FlatList>

                <Loading onRef={(ref) => (this.Loading = ref)}></Loading>

            </View>
        );
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }



    refreshData = () => {
        this.setState({
            pageNo: 1,
            msgList: [],
            isRefresh: true
        }, function () {
            this.getMsgList()
        })
    }

    renderMsgItem({ item, index }) {
        return (
            <View
                key={index}
                style={styles.msgItemContain2}
            >

                <Text style={styles.msgItemTimeText}>{formatTimestamp(item.createTime)}</Text>
                {item.isNewModel == '1' ?
                    <TouchableOpacity style={{ borderWidth: 1, borderColor: '#e1e1e1', borderRadius: 4, paddingHorizontal: 10, paddingTop: 10 }}
                        onPress={() => {
                            console.log('item=', item)
                            if (item.linkUrl && item.linkUrl != '') {

                                let strs = item.linkUrl.split('?')

                                let page = strs[0].replace('app:', '')
                                let params = this.splitParams(item.linkUrl)

                                navigation.navigate(page, params)
                            }
                        }}>
                        <Text style={styles.msgItemTitleText}>{item.title}</Text>

                        <View style={{ height: 0.5, backgroundColor: '#e4e4e4', marginTop: 15, }}></View>
                        <View style={styles.contentContain}>
                            {item.picUrl && item.picUrl != '' ?
                                <AsyncImage
                                    source={{ uri: getImgUrl(item.picUrl) }}
                                    defaultSource={require('source/image/icon_car_default.png')}
                                    style={{ width: 120, height: 90, borderRadius: 4 }}
                                    resizeMode="cover"
                                />
                                : null
                            }


                            <Text style={[styles.contentText, { marginLeft: 5, flex: 1 }]}>{item.content}</Text>

                        </View>

                        <View style={styles.detailContain}>
                            <Text>查看详情</Text>
                            <Image style={styles.detailIcon} source={require('source/image/comm/arrow_gray_icon.png')}></Image>
                        </View>

                    </TouchableOpacity>
                    :
                    item.msgType == 1 ?
                        this.getCarMsgItem(item)

                        :
                        <TouchableOpacity style={{ borderWidth: 1, borderColor: '#e1e1e1', borderRadius: 4, paddingHorizontal: 10, paddingTop: 10 }}
                            onPress={() => {
                                if (item.bizType == '1') {
                                    navigation.navigate('CarDetailPage', {
                                        carId: item.bizId,merchantId:Constant.userInfo.merchantId
                                    })
                                }
                            }}>
                            <Text style={styles.msgItemTitleText}>{item.title}</Text>
                            <View style={{ height: 0.5, backgroundColor: '#e4e4e4', marginTop: 10, marginBottom: 5 }}></View>
                            <Text style={styles.contentText}>{this.getContent(item)}</Text>

                            <View style={styles.detailContain}>
                                <Text>查看详情</Text>
                                <Image style={styles.detailIcon} source={require('source/image/comm/arrow_gray_icon.png')}></Image>
                            </View>
                        </TouchableOpacity>
                }




            </View>
        )

    }

    getCarMsgItem(item) {
        let carInfo = JSON.parse(item.content)
        return (
            <TouchableOpacity style={{ borderWidth: 1, borderColor: '#e1e1e1', borderRadius: 4, paddingHorizontal: 10, paddingTop: 10 }}
                onPress={() => {
                    navigation.navigate('CarDetailPage', {
                        carId: item.bizId,
                        merchantId: carInfo.merchantId
                    })
                }}>
                <Text style={styles.msgItemTitleText}>{item.title}</Text>

                <View style={{ height: 0.5, backgroundColor: '#e4e4e4', marginTop: 15, }}></View>
                <View style={styles.contentContain}>
                    {carInfo.picUrl && carInfo.picUrl != '' ?
                        <Image style={{ width: 120, height: 90, borderRadius: 4 }} source={{ uri: getImgUrl(carInfo.picUrl) }}></Image>
                        : null
                    }


                    <View style={{ flexDirection: 'column', marginLeft: 5, height: 90, justifyContent: 'space-between', flex: 1 }}>

                        <Text style={[styles.contentText2, {}]}>{this.getCarInfoContent1(item, carInfo)}</Text>
                        <Text style={[styles.contentText2, {}]}>{this.getCarInfoContent2(item, carInfo)}</Text>
                        <Text style={[styles.contentText2, {}]}>{this.getCarInfoContent3(item, carInfo)}</Text>


                    </View>


                </View>

                <View style={styles.detailContain}>
                    <Text>查看详情</Text>
                    <Image style={styles.detailIcon} source={require('source/image/comm/arrow_gray_icon.png')}></Image>
                </View>

            </TouchableOpacity>
        )
    }

    getCarInfoContent1(item, carInfo) {
        if (item.bizType == '2' || item.bizType == '3') {
            if (carInfo.registerDate == null || carInfo.registerDate == '' || carInfo.registerDate == 'null') {
                return '指导价：' + getPriceFormat(carInfo.guidePrice)
            } else {
                return getCarRegisterDate(carInfo.registerDate) + ' | ' + getMileFormat(carInfo.mileage)
            }
        } else if (item.bizType == '5') {
            return getCarRegisterDate(carInfo.registerDate) + ' | ' + getMileFormat(carInfo.mileage)
        }

        return ''
    }

    getCarInfoContent2(item, carInfo) {
        if (item.bizType == '2' || item.bizType == '3') {
            if (carInfo.sellerName == null || carInfo.sellerName == '' || carInfo.sellerName == 'null') {
                if (carInfo.onSalesPrice == null || carInfo.onSalesPrice == '' || carInfo.onSalesPrice == 'null') {
                    return '展厅标价：' + getPriceFormat(carInfo.markedPrice)
                } else {
                    return '联盟特价：' + getPriceFormat(carInfo.onSalesPrice)
                }

            } else {
                return '销售员：' + carInfo.sellerName
            }
        } else if (item.bizType == '5') {
            return '意向价：' + getPriceFormat(carInfo.intentionPrice)
        }

        return ''
    }

    getCarInfoContent3(item, carInfo) {
        if (item.bizType == '2' || item.bizType == '3') {
            return carInfo.merchantName
        }

        return ''
    }

    splitParams(str) {
        const index = str.indexOf('?');
        let paramsObj = {};
        if (index !== -1) {
            // 提取 ? 后面的参数部分
            const paramsStr = str.slice(index + 1);
            // 按 & 分割参数
            const paramPairs = paramsStr.split('&');
            paramPairs.forEach((pair) => {
                // 按 = 分割键值对
                const [key, value] = pair.split('=');
                paramsObj[key] = value;
            });
        }

        return paramsObj
    }

    getContent(item) {
        if (item.bizType == '1') {
            if (item.content.indexOf('{') != -1) {
                let contentInfo = JSON.parse(item.content)
                let msgContent = "您的车辆 " + contentInfo.carName + "已被系统管理员移除联盟车源。原因："
                    + contentInfo.expulsionReason + "。";
                return msgContent
            } else {
                return item.content
            }
        } else {
            return item.content
        }
    }

    _onEndReached() {
        console.log('_onEndReached', this.state.showFoot)
        if(this.state.isFirstLoad){
            return null
        }

        if (this.state.showFoot != 0) {
            return null;
        }

        let nextPage = this.state.pageNo + 1

        this.setState({ showFoot: 2, pageNo: nextPage },
            function () {
                this.getMsgList();
            });


    }

    _renderFooter() {
        if (this.state.msgList.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    getMsgList() {

        let params = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            userId: Constant.userInfo.userId,

        }

        if (this.state.msgType != '') {
            params.msgType = this.state.msgType
        } else {
            params.msgTypes = [1, 3]
        }


        HttpUtils.postRequest(HttpUrls.messageQuery, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide()
                }

                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList
                    console.log(resultList)
                    if (resultList.length > 0) {


                        if (resultList.length < 20) {

                            this.setState({
                                showFoot: 1
                            })
                        } else {
                            this.setState({
                                showFoot: 0
                            })
                        }

                        this.setState({
                            msgList: this.state.msgList.concat(resultList),
                        })

                    } else {

                        this.setState({
                            showFoot: 1
                        })
                    }

                    this.setState({
                        isRefresh: false,

                    })
                    if (this.state.isFirstLoad) {
                        DeviceEventEmitter.emit('updateUnreadMsg', {});
                        this.setState({
                            isFirstLoad: false
                        })
                    }
                } else {
                    this.setState({
                        isRefresh: false,
                        isFirstLoad: false
                    })
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide()
                }
                this.setState({
                    isRefresh: false,

                })
            });
    }

};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
    },

    searchContain: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15,
        marginRight: 15,
        backgroundColor: '#fff',
        height: 40,
        borderRadius: 6,
        paddingLeft: 10,
        paddingRight: 10
    },

    searchIcon: {

        width: 20,
        height: 20,
    },

    searchText: {

        marginLeft: 5,
        fontSize: 14,
        color: '#333'
    },
    searchInput: {
        flex: 1,
        marginLeft: 10,
        fontSize: 14,
        color: '#333'
    },

    itemMsgIcon: {
        width: 48,
        height: 48,
        borderRadius: 48,
        backgroundColor: '#f6f6f6'
    },

    msgItemContain: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15,
        marginRight: 15,
        paddingTop: 12,
        paddingBottom: 12,
        borderBottomWidth: 0.5,
        borderBottomColor: '#e4e4e4'

    },

    msgCountContain: {
        backgroundColor: '#ED542E',
        height: 14,
        borderRadius: 14,
        minWidth: 14,
        alignItems: 'center',
        justifyContent: 'center',
        position: 'absolute',
        top: 0,
        right: 0
    },
    msgCountText: {
        fontSize: 8,
        color: '#fff'
    },
    contentContain: {
        flexDirection: 'row',

        flex: 1,
        marginTop: 10,
        marginBottom: 10
    },
    msgItemTitleText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold'
    },
    contentText: {
        marginTop: 5,
        fontSize: 14,
        color: '#999999',
        marginBottom: 10
    },
    contentText2: {

        fontSize: 14,
        color: '#999999',
    },
    timeText: {
        marginTop: 3,
        fontSize: 10,
        color: '#999999'
    },

    msgItemContain2: {


        marginLeft: 15,
        marginRight: 15,
        paddingTop: 12,
        paddingBottom: 12,


    },

    carImg: {
        width: 62,
        height: 62,
        backgroundColor: '#f6f6f6',
        borderRadius: 4
    },
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    msgItemTimeText: {
        marginBottom: 5,
        fontSize: 12,
        color: '#999999',
        width: '100%',
        textAlign: 'center'
    },
    msgTitleText: {

        fontSize: 14,
        color: '#333333',

    },
    detailIcon: {
        width: 18,
        height: 18,
        resizeMode: 'contain'
    },
    detailContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 36,
        borderTopColor: '#e4e4e4',
        borderTopWidth: 0.5
    }
});